package com.party.web.web.controller.member;

import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.activity.Activity;
import com.party.core.model.commune.CIntegralItem;
import com.party.core.model.commune.CIntegralType;
import com.party.core.model.commune.CUserIntegral;
import com.party.core.model.commune.IntegralType;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.commune.ICIntegralItemService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.commune.ICUserIntegralService;
import com.party.core.service.member.IMemberGroupService;
import com.party.web.biz.system.member.MemberBizService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: party
 * @description: 积分项控制器
 * @author: Hua Qunhao
 * @create: 2019-08-12 18:56
 **/
@Controller
@RequestMapping("member/integral/integralItem")
public class IntegralItemController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ICIntegralItemService integralItemService;

    @Autowired
    private ICIntegralTypeService integralTypeService;

    @Autowired
    private ICUserIntegralService userIntegralService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private MemberGroupBizService memberGroupBizService;

    @Autowired
    private MemberBizService memberBizService;


    /**
     * @Description:积分项列表
     * @Param:CIntegralItem
     * @return:ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @RequestMapping("/list")
    public ModelAndView list(CIntegralItem cIntegralItem, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/integralItemList");
        Map<String, Object> params = CommonInput.appendParams(input);
        if (StringUtils.isNotEmpty(cIntegralItem.getName())) {
            params.put("name", cIntegralItem.getName());
        }
        if (StringUtils.isNotEmpty(cIntegralItem.getTypeId())) {
            params.put("typeId", cIntegralItem.getTypeId());
        }
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        List<MemberGroup> memberGroupList = new ArrayList<>();

        if (!Constant.MEMBER_XZGSADMIN.equals(currentUser.getType())) {
            memberGroupList = memberGroupService.getChildWithMyAndName(currentUser.getId());
            List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
            params.put("orgIds", orgIds);
        } else {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(), currentUser.getPartnerId());
        }
        mv.addObject("memberGroupList", memberGroupList);

        if (StringUtils.isNotEmpty(input.getMemberGroupId())) {
            params.put("createBy", input.getMemberGroupId());
        }
        List<CIntegralItem> cIntegralItems = integralItemService.webPageList(params, page);
        mv.addObject("cIntegralItems", cIntegralItems);

        //积分类型
        CIntegralType cIntegralType = new CIntegralType();
        boolean isChild = currentUser.isChild();
        if (isChild) {
            cIntegralType.setCreateBy(currentUser.getPartnerId());
        } else {
            cIntegralType.setCreateBy(currentUser.getId());
        }
        List<CIntegralType> cIntegralTypes = integralTypeService.list(cIntegralType);
        mv.addObject("cIntegralTypes", cIntegralTypes);

        mv.addObject("cIntegralItem", cIntegralItem);
        mv.addObject("input", input);
        mv.addObject("page", page);
        mv.addObject("isChild", isChild);
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        return mv;
    }

    /**
     * @Description:积分项详情
     * @Param:CIntegralItem
     * @return:ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @RequestMapping("/form")
    public ModelAndView form(String id) {
        ModelAndView mv = new ModelAndView("member/integralItemForm");

        CIntegralItem cIntegralItem = null;
        Integer category = 0;
        if (StringUtils.isNotEmpty(id)) {
            cIntegralItem = integralItemService.get(id);

            //是否为推荐类型的积分项
            CIntegralType ciOrg = integralTypeService.get(cIntegralItem.getTypeId());
            category = ciOrg.getCategory();
        }
        mv.addObject("cIntegralItem", cIntegralItem);
        mv.addObject("category", category);

        //积分类型
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        String partnerId = currentUser.getId();
        CIntegralType cIntegralType = new CIntegralType();
        if (currentUser.isChild()) {
            partnerId = currentUser.getPartnerId();
            if (!currentUser.isXzgsAdmin()) {
                //子账号看普通类型积分项____管理员除外
                cIntegralType.setCategory(Integer.valueOf(0));
            }
        }
        cIntegralType.setCreateBy(partnerId);
        List<CIntegralType> cIntegralTypes = integralTypeService.list(cIntegralType);
        mv.addObject("cIntegralTypes", cIntegralTypes);

        List<MemberGroup> memberGroupList = new ArrayList<>();
        if (currentUser.isXzgsAdmin()) {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(), null);
        } else {
            memberGroupList = memberGroupService.getChildWithMyAndName(currentUser.getId());
        }

        mv.addObject("memberGroupList", memberGroupList);

        //是否存在普通等级的--推荐--积分项
        boolean isExistGradeOrdinary = false;
        CIntegralItem item = new CIntegralItem();
        item.setCreateBy(currentUser.getId());
        item.setRecommendGrade(CIntegralItem.CINTEGRALITEM_GRADE_ORDINARY);
        List<CIntegralItem> list = integralItemService.list(item);
        if (list.size() > 0) {
            isExistGradeOrdinary = true;
        }
        mv.addObject("isExistGradeOrdinary", isExistGradeOrdinary);

        //是否存在普通等级的--赠送--积分项
        boolean isExistGiftOrdinary = false;
        CIntegralItem giftItem = new CIntegralItem();
        giftItem.setCreateBy(currentUser.getId());
        giftItem.setGiftGrade(CIntegralItem.CINTEGRALITEM_GRADE_ORDINARY);
        List<CIntegralItem> giftItemlist = integralItemService.list(giftItem);
        if (giftItemlist.size() > 0) {
            isExistGiftOrdinary = true;
        }
        mv.addObject("isExistGiftOrdinary", isExistGiftOrdinary);
        return mv;
    }


    /**
     * @Description:编辑积分项
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(CIntegralItem ciItem, String memberGroupId) {
        try {
            if (StringUtils.isEmpty(ciItem.getName()) || StringUtils.isEmpty(ciItem.getTypeId())) {
                return AjaxResult.error("参数为空");
            }

            CIntegralType cIntegralType = integralTypeService.get(ciItem.getTypeId());

            if (cIntegralType.getCategory() > 0 &&
                    CIntegralItem.CINTEGRALITEM_GRADE_ORDINARY == ciItem.getRecommendGrade()) {
                CIntegralItem cIntegralItem = new CIntegralItem();
                cIntegralItem.setTypeId(cIntegralType.getId());
                cIntegralItem.setRecommendGrade(CIntegralItem.CINTEGRALITEM_GRADE_ORDINARY);
                List<CIntegralItem> list = integralItemService.list(cIntegralItem);
                if (list.size() > 0) {
                    CIntegralItem itemOrg = list.get(0);
                    if (!itemOrg.getId().equals(ciItem.getId())) {
                        return AjaxResult.error("只能存在一个普通等级的推荐/赠送类型积分项");
                    }
                }
            }
            if (!(IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode() == cIntegralType.getCategory())) {
                ciItem.setRecommendGrade(null);
            }
            if (!(IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode() == cIntegralType.getCategory())) {
                ciItem.setGiftGrade(null);
            }

            List<CIntegralItem> list = integralItemService.list(new CIntegralItem(ciItem.getName(), ciItem.getTypeId()));
            if (StringUtils.isEmpty(memberGroupId)) {
                memberGroupId = memberGroupBizService.getXzgsMemberId();
            }
            if (list.size() > 0) {
                CIntegralItem cIntegralItem = list.get(0);
                if (cIntegralItem.getId().equals(ciItem.getId())) {
                    ciItem.setCreateBy(memberGroupId);
                    integralItemService.update(ciItem);
                } else {
                    return AjaxResult.error("积分项已存在");
                }
            } else {
                ciItem.setCreateBy(memberGroupId);
                integralItemService.insert(ciItem);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑积分项异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑积分项异常", e.getMessage());
        }
    }

    /**
     * @Description:删除积分项
     * @Param:id
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping("/delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("参数为空");
            }
            CIntegralItem cIntegralItem = integralItemService.get(id);
            if (cIntegralItem == null) {
                logger.error("积分项不存在");
                return AjaxResult.error("积分项不存在");
            }
            List<CUserIntegral> cUserIntegrals = userIntegralService.listPage(new CUserIntegral(id, "", ""), new Page(0, 1));
            if (cUserIntegrals.size() > 0) {
                logger.error("积分项已分配给用户，不能直接删除");
                return AjaxResult.error("积分项已分配给用户，不能直接删除");
            }
            cIntegralItem.setDelFlag(BaseModel.DEL_FLAG_DELETE);
            integralItemService.update(cIntegralItem);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除积分项异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除积分项异常");
        }
    }

    /**
     * @Description:积分列表
     * @Param:CIntegralItem
     * @return:ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<CIntegralItem> listAll(String typeId, String partnerId, String memberId) {
        try {
            if (StringUtils.isEmpty(typeId)) {
                logger.error("获取全部积分项异常，typdId为空");
                return null;
            }
            String memberGroupId = RealmUtils.getNewCurrentUser().getId();
            HashMap<String, Object> params = Maps.newHashMap();
            params.put("typeId", typeId);
            if (StringUtils.isNotEmpty(partnerId)) {
                memberGroupId = partnerId;
            }
            List<String> orgIds = new ArrayList<>();
            if (StringUtils.isEmpty(memberId)) {
                orgIds = memberGroupService.getChildWithMy(memberGroupId);
            } else {
                orgIds = memberBizService.getMemberGroupIdsByMemberId(memberId);
            }
            params.put("orgIds", orgIds);

            List<CIntegralItem> list = integralItemService.webPageList(params, null);
            return list;
        } catch (Exception e) {
            logger.error("获取全部积分项异常", e);
            return null;
        }
    }

    @RequestMapping("distribute/item/data")
    @ResponseBody
    public AjaxResult distributeData() {

        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        List<String> orgIds = memberGroupService.getChild(currentUser.getId());

        for (String partnerId : orgIds) {
            MemberGroup memberGroup = memberGroupService.get(partnerId);
            HashMap<String, Object> params = Maps.newHashMap();
            params.put("itemName", memberGroup.getRealname());
            params.put("category", Integer.valueOf(0));
            List<CIntegralItem> items = integralItemService.getItemsByNameAndCategory(params);
            for (CIntegralItem item : items) {
                item.setCreateBy(memberGroup.getId());
                integralItemService.update(item);
            }
        }

        return AjaxResult.success();
    }
}
